
import 'package:dio/dio.dart';
import 'dart:async';
import 'dart:io';

import 'package:flutter_demo/config/index.dart';
import 'package:flutter_demo/util/global.dart';

class DioUtils {
  /// global dio object
  static Dio dio;

  /// default options
  static String apiPrefix = Config.apiUrl;
  static const int CONNECT_TIMEOUT = 10000;
  static const int RECEIVE_TIMEOUT = 3000;

  /// http request methods
  static const String GET = 'get';
  static const String POST = 'post';
  static const String PUT = 'put';
  static const String PATCH = 'patch';
  static const String DELETE = 'delete';

  // get
  static Future<Map> get(String url, {data}) async {
    if (data != null) {
      String params = '';
      data.forEach((String key, value) {
        params += '&$key=$value';
      });
      params = params.substring(1);
      return await request('$url?$params', method: GET);
    } else {
      return await request(url, method: GET);
    }
  }

  /// request method
  static Future<Map> request(String url, {data, method}) async {
    data = data ?? {};
    method = method ?? 'GET';

    /// restful 请求处理
    data.forEach((key, value) {
      if (url.indexOf(key) != -1) {
        url = url.replaceAll(':$key', value.toString());
      }
    });

    /// 打印请求相关信息：请求地址、请求方式、请求参数
    print('请求地址：[' + method + '  ' + url + ']');
    print('请求参数：' + data.toString());

    Dio dio = createInstance();
    var result;

    try {
      Response response = await dio.request(url,
          data: data,
          options: new Options(method: method, headers: {
            HttpHeaders.acceptHeader: "*",
            HttpHeaders.contentTypeHeader: 'application/json',
            HttpHeaders.authorizationHeader: 'Bearer ${Global.TOKEN}'
          }));

      result = response.data;
      
      /// 打印响应相关信息
      print('响应数据：' + response.toString());
    } on DioError catch (e) {
      /// 打印请求失败相关信息
      print('请求出错：' + e.toString());
    }

    return result;
  }

  /// 创建 dio 实例对象
  static Dio createInstance() {
    if (dio == null) {
      var options = BaseOptions(
          connectTimeout: 150000,
          receiveTimeout: 150000,
          responseType: ResponseType.json,
          validateStatus: (status) {
            // 不使用http状态码判断状态，使用AdapterInterceptor来处理（适用于标准REST风格）
            return true;
          },
          baseUrl: Config.apiUrl,
          headers: {
            HttpHeaders.acceptHeader: "*",
            HttpHeaders.contentTypeHeader: 'application/json',
            HttpHeaders.authorizationHeader: 'Bearer ${Global.TOKEN}'
          });

      dio = new Dio(options);
    }

    return dio;
  }

  /// 清空 dio 对象
  static clear() {
    dio = null;
  }
}
